//
//  CommentViewController.swift
//  甜言蜜语
//
//  Created by 王剑伟 on 16/5/31.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import SVProgressHUD
class CommentViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate,NewsDetailHotReplyFooterCellDelegate,RGFadeDelegate {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var textField: UITextField!
    var hotUrl: String = ""
    var timeUrl: String = ""
    var requestID: String!
    var type: String = ""
    var isshoucang: Bool?
    var model: [NewsDetailHotReplyModel]?{
        didSet{
            self.tableView.reloadData()
        }
    }
    var msg: regiestInfo?
    var rgFadeView: RGFadeView?
    override func viewDidLoad() {
        super.viewDidLoad()
        publicMethod.setHUDStyle()
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.textField.delegate = self
        
        self.title = "回复"
        let cellNib = UINib(nibName: "NewsDetailHotReplyFooterCell", bundle: nil)
        
        self.tableView.registerNib(cellNib, forCellReuseIdentifier: "NewsDetailHotReplyFooterCell")
        
        publicMethod.hiddleExtendCellForTableView(self.tableView)
        
        self.getHotReply()
        
         NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CommentViewController.getHotReply), name: hotBtnClicked_noti, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CommentViewController.getTimeReply), name: timeBtnClicked_noti, object: nil)
        
         NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CommentViewController.userTouched_noti(_:)), name: "userHeadClicked_noti_head", object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.reloaData), name: "relodData", object: nil)
        

    
    }
   
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
    deinit {
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //收藏按钮点击事件
    @IBAction func collectBtnDown(sender: UIButton) {
        DataTool.collectionNews((self.requestID)!,isshoucang: self.isshoucang!, type:"行业资讯", completionHandler: { (newsData)
            in
            guard let newsDetailData = newsData else {
                return
            }
            self.msg = newsDetailData
            SVProgressHUD.showSuccessWithStatus(self.msg?.msg)
          
            
        })
    }
    //跳转到回复页
    @IBAction func commenBtnClicked(sender: UIButton){
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ReplyVC") as! ReplyVC
       
        vc.id = requestID
        vc.type = self.type
        self.navigationController?.pushViewController(vc, animated: true)
    }

    //MARK:tableViewDataSource
    
    func tableView(tableView: UITableView,heightForHeaderInSection section: Int) -> CGFloat{
        if self.model?.count == 0 || self.model?.count == nil{
            return 0
        }else{
            return 50
        }
     
    }
   func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
         let cell = tableView.dequeueReusableCellWithIdentifier("NewsDetailHotReplyFooterCell") as! NewsDetailHotReplyFooterCell
        let cellInfo = self.model![indexPath.row]
        cell.setCellContentWithCellInfo(cellInfo.message)
        
        return cell.cellHeight!
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
     
        let sectionView = NSBundle.mainBundle().loadNibNamed("HotReplySection", owner: nil, options: nil).last as? HotReplySection
        
        return sectionView
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.model?.count == 0 || self.model?.count == nil{
            return 0
        }else{
             return model!.count
        }
       
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("NewsDetailHotReplyFooterCell") as! NewsDetailHotReplyFooterCell
        let cellInfo = self.model![indexPath.row]
        cell.type = self.type
        cell.headType = "回复"
        cell.modelList = cellInfo
        return cell
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("ReplyVC") as! ReplyVC
        
        vc.id = self.model![indexPath.row].id
        vc.type = self.type
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
       
        if (rgFadeView == nil) {
            rgFadeView = RGFadeView.init(frame: kScreen_frame)
            rgFadeView?.delegate = self
            self.view.addSubview(rgFadeView!)
        }
        rgFadeView?.msgTextView.becomeFirstResponder()

        
        return true
    }
    
    
    //MARK:RGFadeViewDelegate
    //回复评论
    func sendBtnDown(text: String) {
        if ApplicationDelegate.isLogin(){
            var jsonData = ["docid": requestID, "message": text]
            if self.type == "活动"{
                jsonData = ["actid": requestID, "message": text]
            }
            
            
            DataTool.sendComment(jsonData,type: self.type, completionHandler: { (isSuccess) -> Void in
                if isSuccess {
                    SVProgressHUD.showSuccessWithStatus("回复成功")
                    self.getHotReply()
                    
                } else {
                    SVProgressHUD.showErrorWithStatus("回复失败")
                   
                }
            })

        }else{
            SVProgressHUD.showInfoWithStatus("请先登录")
        }
    }

    //MARK:NETWORKING
    // 热门
    func getHotReply(){
        if self.type == "行业"{
            hotUrl = String(format: "%@infomation/comment/\(self.requestID)",BaseUrl)
            
        }else{
            hotUrl = String(format: "%@activity/comment/\(self.requestID)",BaseUrl)
           
        }
        DataTool.hotReplyInfo(hotUrl, completionHandler:{ (newModel) in
            guard let newDataes = newModel else {
                return
            }
            print(newDataes)
            self.model = newDataes
        })
       

    }
   //时间
    func getTimeReply(){
        if self.type == "行业"{
            timeUrl = String(format: "%@infomation/comment/timeorder/\(self.requestID)",BaseUrl)
        }else{
            timeUrl = String(format: "%@activity/comment/timeorder/\(self.requestID)",BaseUrl)
           
        }

        DataTool.timeReplyInfo(timeUrl, completionHandler: { (newModel) in
            guard let newDataes = newModel else {
                return
            }
            print(newDataes)
            self.model = newDataes
        })

    }
    //MARK:noti
    func userTouched_noti(notification:NSNotification){
        
        let id = notification.object?.valueForKey("id") as! String
       
       self.userTouched(Int(id)!)
        
    }

    //头像点击
    func userTouched(userID: Int) {
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("UserHomeTableViewController") as! UserHomeTableViewController
        vc.userId = userID
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //删除自己的评论
    func reloaData() {
        self.getHotReply()
    }

}

